package com.wx.io.netty.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty client
 *
 * @author wangxun
 * @version 1.0
 * @description: netty client
 * @date 2021/1/5 5:07 下午
 */
public class NettyClient {
    public static void main(String[] args) {
        NioEventLoopGroup work = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(work)
                .channel(NioSocketChannel.class)
                .remoteAddress("192.168.4.224", 9999)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("初始化client...");
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new MyInBound());
                    }
                });
        try {
            ChannelFuture connect = bootstrap.connect().sync();
            Channel channel = connect.channel();
            ByteBuf byteBuf = Unpooled.copiedBuffer("Hello Netty 这就是字节数据".getBytes());
            channel.writeAndFlush(byteBuf).sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
